//
//  PTStuLifeServiceMyPartJobViewController.m
//  PlanTech
//  生活服务-我的兼职页面
//  Created by ruifeng song on 2018/7/11.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "PTStuLifeServiceMyPartJobViewController.h"
#import "PTStuLifeServiceHeaderView.h"
#import "PTStuLSPartJobDetailViewController.h"
#import "PTCoreManager+LifeService.h"
#import "PTCoreObject+LifeService.h"
#import "PTStuLSMyPartJobCell.h"

@interface PTStuLifeServiceMyPartJobViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,MyPartJobCellDelegate,LifeServiceHeaderViewDelegate,UIAlertViewDelegate>
{
    NSInteger currentPage;
    
    int allMissionPageNum;
    int waitFinishPageNum;
    int waitCommentMissionPageNum;
}

@property(nonatomic,strong)UITableViewCell * currentPartJobCell;

@property(nonatomic,copy)NSString *missionUUID;

@property(nonatomic,assign)int currentPageNum;
@property(nonatomic,assign)BOOL isRefreshData;
@property(nonatomic,strong)UILabel *bottomLabel;

@property (nonatomic,strong)PTStuLifeServiceHeaderView *headerView;

@property (nonatomic,strong)UIScrollView * myPartJobScrolView;

@property(nonatomic,assign)PTLifeServiceMissionStatus serviceStatus;

@property (nonatomic,strong)UITableView *allMissonTableView;
@property (nonatomic,strong)UITableView *waitFinishMissionTableView;
@property (nonatomic,strong)UITableView *waitCommentMissionTableView;

//全部
@property(nonatomic,strong)NSMutableArray *allMissonArray;

//待完成
@property(nonatomic,strong)NSMutableArray *waitFinsihMissionArray;

//待评价
@property(nonatomic,strong)NSMutableArray *waitCommentMissionArray;

@end

@implementation PTStuLifeServiceMyPartJobViewController

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(NSMutableArray *)allMissonArray
{
    if (_allMissonArray ==nil) {
        
        _allMissonArray = [NSMutableArray array];
    }
    return _allMissonArray;
}

-(NSMutableArray *)waitFinsihMissionArray
{
    if (_waitFinsihMissionArray == nil) {
        
        _waitFinsihMissionArray = [NSMutableArray array];
    }
    return _waitFinsihMissionArray;
}

-(NSMutableArray *)waitCommentMissionArray
{
    if (_waitCommentMissionArray == nil) {
        
        _waitCommentMissionArray = [NSMutableArray array];
    }
    return _waitCommentMissionArray;
}

//在页面出现的时候就将黑线隐藏起来

-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

//在页面消失的时候就让navigationbar还原样式

-(void)viewWillDisappear:(BOOL)animated{
    
    [self.navigationController.navigationBar setShadowImage:nil];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"我的兼职";
    
    self.view.backgroundColor = BaseViewBackgroundColor;
    
    self.isRefreshData = NO;
    currentPage = 0;
    
    self.serviceStatus = PTLifeServiceMission_AllStatus;
    self.currentPageNum = [self getCurrentRequestPageWithRefresh:YES];

    [self createView];
    
    [self requestData];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(requestData) name:kPT_Global_Notification_RefreshMyPartJobList object:nil];
}

-(void)createView
{
    UIImageView * backImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0,ScreenWidth, 40)];
    [backImageView setImage:[UIImage imageNamed:@"nav_bar_bg"]];
    backImageView.userInteractionEnabled = YES;
    [self.view addSubview:backImageView];
    
    [backImageView addSubview:self.headerView];
    
    _myPartJobScrolView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 40, ScreenWidth, ScreenHeight - TOP_HEIGHT - 40)];
    _myPartJobScrolView.pagingEnabled = YES;
    _myPartJobScrolView.contentSize = CGSizeMake(ScreenWidth * 3, ScreenHeight - TOP_HEIGHT - 40);
    _myPartJobScrolView.showsHorizontalScrollIndicator = NO;
    _myPartJobScrolView.delegate = self;
    [self.view addSubview:_myPartJobScrolView];
    
    [self.view addSubview:self.myPartJobScrolView];
    
    self.allMissonTableView = [self createTableViewWithPageTag:0];
    [self.myPartJobScrolView addSubview:self.allMissonTableView];
    
    self.waitFinishMissionTableView = [self createTableViewWithPageTag:1];
    [self.myPartJobScrolView addSubview:self.waitFinishMissionTableView];
    
    self.waitCommentMissionTableView = [self createTableViewWithPageTag:2];
    [self.myPartJobScrolView addSubview:self.waitCommentMissionTableView];
}

-(PTStuLifeServiceHeaderView *)headerView
{
    if (_headerView == nil) {
        
        _headerView = [[PTStuLifeServiceHeaderView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth,40) titleArray:[NSArray arrayWithObjects:@"全部",@"待完成",@"待评价", nil]];
        _headerView.delegate = self;
        
        CGFloat buttonW = ScreenWidth/3;
        
        _bottomLabel = [[UILabel alloc]initWithFrame:CGRectMake(((buttonW - 50)/2), 40 - 3 -5,50, 3)];
        _bottomLabel.backgroundColor = [UIColor whiteColor];
        _bottomLabel.layer.cornerRadius = 1.5;
        _bottomLabel.layer.masksToBounds = YES;
        [_headerView addSubview:_bottomLabel];
    }
    return _headerView;
}

-(void)updateUnderlineLocationWithTag:(NSInteger)pageTag
{
    CGFloat buttonW = ScreenWidth/3;
    CGFloat orginx = ((buttonW - 50)/2);
    
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.bottomLabel setFrame:CGRectMake((buttonW * pageTag) + orginx, 40-3-5, 50, 3)];
        
    }];
}

-(UITableView *)createTableViewWithPageTag:(NSInteger)pageTag
{
    UITableView * tv = [[UITableView alloc]initWithFrame:CGRectMake(ScreenWidth * pageTag,0, ScreenWidth, ScreenHeight - TOP_HEIGHT - 40) style:UITableViewStylePlain];
    tv.delegate = self;
    tv.dataSource = self;
    tv.backgroundColor = [UIColor clearColor];
    tv.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    WeakSelf;
    tv.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        if (weakSelf.isRefreshData) {
            
            return ;
        }
        
        //下拉刷新
        weakSelf.currentPageNum = [weakSelf getCurrentRequestPageWithRefresh:YES];
        [weakSelf requestData];
        
    }];
    
    tv.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if (weakSelf.isRefreshData) {
            
            return ;
        }
        //上拉加载
        weakSelf.currentPageNum = [weakSelf getCurrentRequestPageWithRefresh:NO];
        [weakSelf requestData];
    }];
    
    return tv;
}

-(int)getCurrentRequestPageWithRefresh:(BOOL)isHeaderRefreshing
{
    if (self.serviceStatus == PTLifeServiceMission_AllStatus) {
        if (isHeaderRefreshing) {
            allMissionPageNum = 1;
        }
        else
        {
            allMissionPageNum++;
        }
        return allMissionPageNum;
    }
    else if (self.serviceStatus == PTLifeServiceMission_NormalStatus)
    {
        if (isHeaderRefreshing) {
            waitFinishPageNum = 1;
        }
        else
        {
            waitFinishPageNum ++;
        }
        return waitFinishPageNum;
    }
    else if (self.serviceStatus == PTLifeServiceMission_FinishStatus)
    {
        if (isHeaderRefreshing) {
            waitCommentMissionPageNum = 1;
        }
        else
        {
            waitCommentMissionPageNum ++;
        }
        return waitCommentMissionPageNum;
    }
    return 1;
}

-(void)requestData
{
    [self requestMyMissionListDataWithStatus:self.serviceStatus pageNum:self.currentPageNum];
}

//获取我的兼职数据
-(void)requestMyMissionListDataWithStatus:(PTLifeServiceMissionStatus)status pageNum:(NSInteger)pageNum
{
    self.isRefreshData = YES;
    
    SINAUserModel *userModel = [[SINACommonUserHelper share]getUserModel];
    
    WeakSelf;
    [[PTCoreManager shareInstance]performGetMyMissionsWithStatus:status userUUID:userModel.userUid page:pageNum num:10 Completion:^(id _Nullable retObject, NSError * _Nullable retError) {
        
        weakSelf.isRefreshData = NO;
        
        DLog(@"%@",retObject);
        
        if (retObject) {
            
            if ([retObject isKindOfClass:[PTMJsonResult class]]) {
                
            }
            else if ([retObject isKindOfClass:[NSArray class]])
            {
                [weakSelf ChangeResponseDataWithArray:retObject];
            }
            else
            {
                 //请求失败
            }
        }
        
    }];
}

-(void)ChangeResponseDataWithArray:(NSArray *)obj
{
    if (self.serviceStatus == PTLifeServiceMission_AllStatus) {
        
        if (self.currentPageNum ==1) {
            [self.allMissonArray removeAllObjects];
            [self.allMissonTableView.mj_header endRefreshing];
            [self.allMissonTableView.mj_footer resetNoMoreData];
        }
        else
        {
            [self.allMissonTableView.mj_footer endRefreshing];
        }
        [self.allMissonArray addObjectsFromArray:obj];
        [self.allMissonTableView reloadData];
        
        if (obj.count < 10) {
            
            [self.allMissonTableView.mj_footer endRefreshingWithNoMoreData];
        }
    }
    else if (self.serviceStatus == PTLifeServiceMission_NormalStatus)
    {
        if (self.currentPageNum ==1) {
            
            [self.waitFinsihMissionArray removeAllObjects];
            [self.waitFinishMissionTableView.mj_header endRefreshing];
            [self.waitFinishMissionTableView.mj_footer resetNoMoreData];
        }
        else
        {
            [self.waitFinishMissionTableView.mj_footer endRefreshing];
        }
        [self.waitFinsihMissionArray addObjectsFromArray:obj];
        [self.waitFinishMissionTableView reloadData];
        
        if (obj.count < 10) {
            
            [self.waitFinishMissionTableView.mj_footer endRefreshingWithNoMoreData];
        }
    }
    else if (self.serviceStatus == PTLifeServiceMission_FinishStatus)
    {
        if (self.currentPageNum ==1) {
            [self.waitCommentMissionArray removeAllObjects];
            [self.waitCommentMissionTableView.mj_header endRefreshing];
            [self.waitCommentMissionTableView.mj_footer resetNoMoreData];
        }
        else
        {
            [self.waitCommentMissionTableView.mj_footer endRefreshing];
        }
        [self.waitCommentMissionArray addObjectsFromArray:obj];
        [self.waitCommentMissionTableView reloadData];
        
        if (obj.count<10) {
            [self.waitCommentMissionTableView.mj_footer endRefreshingWithNoMoreData];
        }
    }
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.serviceStatus == PTLifeServiceMission_AllStatus) {
        
        return self.allMissonArray.count;
    }
    else if(self.serviceStatus == PTLifeServiceMission_NormalStatus)
    {
       return self.waitFinsihMissionArray.count;
    }
    else if (self.serviceStatus == PTLifeServiceMission_FinishStatus)
    {
       return self.waitCommentMissionArray.count;
    }
    return 0;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 194;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * MyPartJobListCellIdentifier = @"MyPartJobListCell";
    
    PTStuLSMyPartJobCell * myPartJobListCell = [tableView dequeueReusableCellWithIdentifier:MyPartJobListCellIdentifier];
    if (myPartJobListCell == nil) {
        
        myPartJobListCell  = [[PTStuLSMyPartJobCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyPartJobListCellIdentifier];
        myPartJobListCell.selectionStyle = UITableViewCellSelectionStyleNone;
        myPartJobListCell.jobDelegate = self;
    }
    if (self.serviceStatus == PTLifeServiceMission_AllStatus) {
       
        [myPartJobListCell updateServiceMyPartJobCellWith:[self.allMissonArray objectAtIndex:indexPath.row]];
    }
    else if(self.serviceStatus == PTLifeServiceMission_NormalStatus)
    {
        [myPartJobListCell updateServiceMyPartJobCellWith:[self.waitFinsihMissionArray objectAtIndex:indexPath.row]];
    }
    else if (self.serviceStatus == PTLifeServiceMission_FinishStatus)
    {
        [myPartJobListCell updateServiceMyPartJobCellWith:[self.waitCommentMissionArray objectAtIndex:indexPath.row]];
    }
    return myPartJobListCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LifeServiceMyMissionsModel * listModel = nil;
    
    if (self.serviceStatus == PTLifeServiceMission_AllStatus) {
    
        listModel = [self.allMissonArray objectAtIndex:indexPath.row];
    }
    else if (self.serviceStatus == PTLifeServiceMission_NormalStatus)
    {
        listModel = [self.waitFinsihMissionArray objectAtIndex:indexPath.row];
    }
    else if (self.serviceStatus == PTLifeServiceMission_FinishStatus)
    {
        listModel = [self.waitCommentMissionArray objectAtIndex:indexPath.row];
    }
    
    PTStuLSPartJobDetailViewController * partJobDetailViewController = [[PTStuLSPartJobDetailViewController alloc]init];
    partJobDetailViewController.missionUUID = listModel.uuid;
    [partJobDetailViewController setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:partJobDetailViewController animated:YES];
}

#pragma mark --
#pragma mark --  UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    CGFloat pageWidth = self.myPartJobScrolView.frame.size.width;
    
    int pageIndex = floor((self.myPartJobScrolView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    
    if (pageIndex == currentPage) {
        
        return;
    }
    currentPage = pageIndex;
    
    [self updateUnderlineLocationWithTag:currentPage];
    
    if (currentPage ==0) {
        self.serviceStatus = PTLifeServiceMission_AllStatus;
    }
    else if (currentPage ==1)
    {
        self.serviceStatus = PTLifeServiceMission_NormalStatus;
    }
    else if (currentPage == 2)
    {
        self.serviceStatus = PTLifeServiceMission_FinishStatus;
    }
    
    [self  requestData];
}

#pragma mark -  MyPartJobCellDelegate Method
//删除订单
-(void)onClickDeletePartJobItem:(PTStuLSMyPartJobCell *)myPartJobCell
{
    self.missionUUID = myPartJobCell.missionUUID;
    
    UIAlertView * alertView  =[[UIAlertView alloc]initWithTitle:nil message:@"确定删除此订单？\n（删除后不可恢复）" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.tag = 22;
    [alertView show];
}

//完成兼职
-(void)onClickFinishPartJobItem:(PTStuLSMyPartJobCell *)myPartJobCell
{
    self.currentPartJobCell = myPartJobCell;
    
    UIAlertView * alertView  =[[UIAlertView alloc]initWithTitle:nil message:@"确定已完成该任务？\n（对方确认并评价后即可完成任务）" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.tag = 33;
    [alertView show];
}

#pragma mark - LifeServiceHeaderViewDelegate Method
-(void)didSelectedHeaderMenuItemIndex:(NSInteger)itemIndex
{
    if (itemIndex == currentPage) {
        
        return;
    }
    currentPage = itemIndex;
    
    [self updateUnderlineLocationWithTag:currentPage];
    [self.myPartJobScrolView setContentOffset:CGPointMake(ScreenWidth * itemIndex, 0) animated:YES];
    
    if (currentPage ==0) {
        self.serviceStatus = PTLifeServiceMission_AllStatus;
    }
    else if (currentPage ==1)
    {
        self.serviceStatus = PTLifeServiceMission_NormalStatus;
    }
    else if (currentPage == 2)
    {
        self.serviceStatus = PTLifeServiceMission_FinishStatus;
    }
    
    [self  requestData];
}

#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag ==22 && buttonIndex ==1) {
        
        WeakSelf;
        [[PTCoreManager shareInstance]performPostMissionDeleteWithUUID:self.missionUUID Completion:^(PTMJsonResult * retObject, NSError * _Nullable retError) {
            if (retObject) {
                
                if ([retObject.code integerValue] == kPTCore_Response_Code) {
                    
                    [weakSelf requestData];
                    
                    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已删除" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alertView show];
                }
            }
            else
            {
                UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"提交错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }
            
        }];
    }
    else if(alertView.tag ==33 && buttonIndex == 1)
    {
        LifeServiceMyMissionsModel * listModel = nil;
        
        if (self.serviceStatus == PTLifeServiceMission_AllStatus) {
            
            NSIndexPath * indexPath = [self.allMissonTableView indexPathForCell:self.currentPartJobCell];
            listModel = [self.allMissonArray objectAtIndex:indexPath.row];
        }
        else if (self.serviceStatus == PTLifeServiceMission_NormalStatus)
        {
            NSIndexPath * indexPath = [self.waitFinishMissionTableView indexPathForCell:self.currentPartJobCell];
            listModel = [self.waitFinsihMissionArray objectAtIndex:indexPath.row];
        }
        else if (self.serviceStatus == PTLifeServiceMission_FinishStatus)
        {
            NSIndexPath * indexPath = [self.waitCommentMissionTableView indexPathForCell:self.currentPartJobCell];
            listModel = [self.waitCommentMissionArray objectAtIndex:indexPath.row];
        }
        
        SINAUserModel *userModel = [[SINACommonUserHelper share]getUserModel];
        
        WeakSelf;
        [[PTCoreManager shareInstance]performPostMissionFinishWithUserName:userModel.userRealName serviceOwnerUUID:listModel.employer.uuid serviceUUID:listModel.serviceUUID type:[listModel.type integerValue] missionUUID:listModel.uuid Completion:^(PTMJsonResult * retObject, NSError * _Nullable retError) {
            
            if (retObject) {
                
                if ([retObject.code integerValue] == kPTCore_Response_Code) {
                    
                    [weakSelf requestData];
                    
                    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已完成" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alertView show];
                }
            }
            else
            {
                UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"提交错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }
        }];
    }
}

-(void)dismiss
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
